import { MessageBox } from 'element-ui'
import { listUnreadNotice, markNoticeRead } from '@/api/system/notice'

let running = false

export async function checkUnreadNoticesOnce() {
  if (running) return
  running = true
  try {
    const res = await listUnreadNotice()
    const notices = res.data || res.rows || []
    for (const n of notices) {
      const html = `<div style="max-height:55vh;overflow:auto;padding:8px 4px;">
        <div style="font-size:16px;font-weight:600;margin-bottom:6px;">${n.noticeTitle || ''}</div>
        ${n.noticeType === '2' && n.endTime ? `<div style='color:#999;margin-bottom:6px;'>截止日期：${n.endTime}</div>` : ''}
        <div>${n.noticeContent || ''}</div>
      </div>`
      // 直到用户点击已读
      await new Promise((resolve, reject) => {
        MessageBox.confirm(html, '公告未读提醒', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '已读',
          cancelButtonText: '稍后再看',
          distinguishCancelAndClose: true,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          type: 'warning'
        }).then(async () => {
          try { await markNoticeRead(n.noticeId) } catch (e) {}
          resolve()
        }).catch(() => {
          // 取消：不标记已读，下次仍提示
          resolve()
        })
      })
    }
  } catch (e) {
    // ignore
  } finally {
    running = false
  }
}
